package com.kevin.permission.common;

import com.kevin.permission.exception.ParamsException;
import com.kevin.permission.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {

    public ModelAndView resolveException(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse, Object o, Exception ex) {
        String url=httpServletRequest.getRequestURI().toString();
        ModelAndView mv=null;
        String defaultMsg="System error";

        //项目要求所有请求json数据，都是要.json结尾
        if (url.endsWith(".json")){
            if (ex instanceof PermissionException || ex instanceof ParamsException){
                JsonData result=JsonData.fail(ex.getMessage());
                mv=new ModelAndView("jsonView",result.toMap());
            }else{
                log.error("unknow json exception,url:"+url);
                JsonData result=JsonData.fail(defaultMsg);
                mv=new ModelAndView("jsonView",result.toMap());
            }
        }else if(url.endsWith(".page")){ // 这里我们要求项目中所有请求page页面，都使用.page结尾
            log.error("unknow json exception,url:"+url);
            JsonData result=JsonData.fail(defaultMsg);
            mv=new ModelAndView("exception",result.toMap());
        }else{
            log.error("unknow json exception,url:"+url);
            JsonData result=JsonData.fail(defaultMsg);
            mv=new ModelAndView("jsonView",result.toMap());
        }
        return mv;
    }

}
